package com.mktneutral.etf;

import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

/**
 * Created with IntelliJ IDEA. User: JVigil0515c Date: 8/16/12 Time: 2:05 AM To
 * change this template use File | Settings | File Templates.
 */
public class MyCompletionHandler extends AsyncCompletionHandler<Response> {
	private ETF etf;
	public Logger logger;

	public MyCompletionHandler(ETF etf) {
		logger = LoggerFactory.getLogger(MyCompletionHandler.class);
		this.etf = etf;
	}

	public Response onCompleted(Response response) throws Exception {
		String[] lines = response.getResponseBody().split("\n");
		String quotePrefix = "http://download.finance.yahoo.com/d/quotes.csv?s=";
		String quoteSuffix = "&f=l1";

		for (int i = 1; i < lines.length - 1; i++) {
			etf.processLine(lines[i].trim());
		}

		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		Future<?> f = asyncHttpClient.prepareGet(quotePrefix + etf.getTicker() + quoteSuffix)
				.execute(new AsyncCompletionHandler<Response>() {
					@Override
					public Response onCompleted(Response response)
							throws Exception {
						etf.setLastPrice(Double.parseDouble(response
								.getResponseBody().trim()));

						logger.info( "Finished " + etf.getTicker() );
						return response;
					}
				});
		f.get(2000, TimeUnit.MILLISECONDS);

		return response;
	}

	public void onThrowable(Throwable t) {
		System.out.println("in onThrowable()");
	}
}
